package ch.electronet.wjw.web.actions.ajax.tree;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class FileEntry implements Node {

	private static Map<String, FileEntry> entries = new HashMap<String, FileEntry>();

	private List<FileEntry> children;
	private boolean toggle;
	private final File file;

	public FileEntry(File file) {
		this.file = file;
		final FilenameFilter filenameFilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".jpg");
			}
		};
		FileFilter filter = new FileFilter() {
			public boolean accept(File file) {
				return (file.isDirectory() && !file.getName().endsWith("thumbs")) && file.list(filenameFilter).length > 0;
			}
		};
		children = new LinkedList<FileEntry>();
		for (File f : file.listFiles(filter)) {
			children.add(new FileEntry(f));
		}
		entries.put(getId(), this);
	}

	public static FileEntry getById(String id) {
		Map<String, FileEntry> en = entries;
		if (entries.size() == 0) {
			new FileEntry(new File(id));
		}
		return entries.get(id);
	}

	public String getId() {
		return file.getAbsolutePath();
	}

	public String getLabel() {
		return file.getName();
	}

	public boolean isLeaf() {
		return !hasChildren();
	}

	public boolean hasChildren() {
		return children.size() != 0;
	}

	public List<FileEntry> getChildren() {
		return children;
	}

	public void setChildren(List<FileEntry> children) {
		this.children = children;
	}

	public void toggle() {
		toggle = !toggle;
	}

	public boolean isToggle() {
		return toggle;
	}
}
